package com.cooper.scraper.show;

import java.util.ArrayList;
import java.util.List;

import com.cooper.scraper.R;
import com.cooper.scraper.ResourceCollector;
import com.cooper.scraper.ResourceScraperRunner;
import com.cooper.scraper.RunnerSubscribe;
import com.cooper.scraper.ScraperException;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

public class OnlineFanartAdapter<T extends OnlineFanartResource> extends
		FanartAdapter<T> implements RunnerSubscribe {

	protected Context context;

	private List<T> resources = new ArrayList<T>();

	private ResourceScraperRunner<T> runner;
	private boolean downloading = false;
	private ResourceCollector<T> mediaCollector;

	private int maxRequestPos = 0;

	public OnlineFanartAdapter(Context context, ResourceScraperRunner<T> runner) {
		super();
		this.context = context;
		this.runner = runner;
		runner.subscribe(this);
	}

	public void setResourceCollector(ResourceCollector<T> mediaCollector) {
		if (this.mediaCollector != null)
			runner.cancel(this);
		this.mediaCollector = mediaCollector;
	}

	public ResourceCollector<T> getResourceCollection() {
		return mediaCollector;
	}

	@Override
	public void refresh() {
		runner.cancel(this);
		destroyResources();
		resources.clear();
		mediaCollector.reset();
		fanartsShow.resetFanart();
		notifyDataSetChanged();
		try {
			runner.listResource(mediaCollector);
			downloading = true;
			if (dataChangedListener != null)
				dataChangedListener.dataWaiting();
		} catch (ScraperException e) {
			Toast.makeText(
					context,
					context.getResources().getString(
							R.string.toast_scraper_error), Toast.LENGTH_LONG)
					.show();
		}

	}

	private void prepareNextPage() {
		if (!downloading && mediaCollector.hasNextPage()
				&& (maxRequestPos >= (resources.size() - 1))) {
			mediaCollector.nextPage();
			try {
				runner.listResource(mediaCollector);
				downloading = true;
				if (dataChangedListener != null)
					dataChangedListener.dataWaiting();
			} catch (ScraperException e) {
				Toast.makeText(
						context,
						context.getResources().getString(
								R.string.toast_scraper_error),
						Toast.LENGTH_LONG).show();
			}

		}
	}

	@Override
	public void destroy() {
		runner.cancelSubscribe(this);
		destroyResources();
	}

	@Override
	public int getCount() {
		return resources.size();
	}

	@Override
	public Object getItem(int position) {
		return resources.get(position);
	}

	@Override
	public long getItemId(int arg0) {
		return arg0;
	}

	@Override
	protected T getResource(int position) {
		return resources.get(position);
	}

	@Override
	protected void onShowView(T resource, int position) {
		if (position > maxRequestPos) {
			maxRequestPos = position;
		}
		prepareNextPage();
	}

	@SuppressWarnings("unchecked")
	@Override
	public void onDownloadComplete(String key, Object data) {
		ResourceCollector<T> result = (ResourceCollector<T>) data;
		downloading = false;
		if (!result.noResult()) {
			resources.addAll(result.getMedias());
			Log.d("OnlineMovieFanartAdapter",
					"downloadComplete:" + resources.size());
			notifyDataSetChanged();
			prepareNextPage();

		} else if (resources.isEmpty() && dataChangedListener != null) {

			dataChangedListener.noResultData();
		}
		if (!downloading && (dataChangedListener != null))
			dataChangedListener.dataComplete();
	}

	@Override
	public void onDownloadFail(String key, int errorCode) {
		// resultMedias.nextPage();?????

		downloading = false;
		if (dataChangedListener != null) {
			if (resources.isEmpty()) {
				dataChangedListener.noResultData();
			}
			dataChangedListener.dataComplete();
		}
		Toast.makeText(
				context,
				context.getResources().getString(
						R.string.toast_download_next_page_fail),
				Toast.LENGTH_LONG).show();

	}

	@Override
	public void onDownloadCancel(String key) {
	}

	@Override
	public boolean subscribed(String key) {
		if (mediaCollector != null) {
			return mediaCollector.subscribed(key);
		} else
			return false;
	}

	private void destroyResources() {
		for (T resource : resources) {
			resource.destroy();
		}
	}

}
